//
//  SpecialNewsListViewController.m
//  suRead
//
//  Created by 李 诗洋 on 16/1/20.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "SpecialNewsListViewController.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "UIViewController+HUD.h"
#import "UIImageView+WebCache.h"
#import "ServiceNews.h"

#import "M_SpecialNews.h"

#import "NewsCell.h"
#import "NewsImageCell.h"
#import "NewsFocusCell.h"
#import "NewsAdvCell.h"

#import "NewsDetailViewController.h"
#import "NewsAlbumViewController.h"
#import "NewsWebViewController.h"
#import "ShareService.h"

#import <MobLink/MobLink.h>
#import <MobLink/MLSDKScene.h>

#define ScreenRectHeight [UIScreen mainScreen].applicationFrame.size.height
#define ScreenRectWidth [UIScreen mainScreen].applicationFrame.size.width

@interface SpecialNewsListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong)NSArray *focusNews;
@property (nonatomic,strong)NSMutableArray *listNews;
@property (nonatomic,assign)NSInteger selectedIndex;
@property (weak, nonatomic) IBOutlet UIView *topViewBar;

@property (nonatomic,strong) IBOutlet UITableView *newsTableView;
@property (nonatomic,strong)NSURLSessionDataTask *requestHandle;
@property (nonatomic,assign)NSInteger currentPageIndex;

@property (nonatomic,strong)NewsFocusCell *focusHandle;

@property (nonatomic, copy) NSString *mobid;

@property (nonatomic,strong) UIScrollView *headerScrollView;
@property (nonatomic,strong) NSMutableArray *tagsArray;

@end

@implementation SpecialNewsListViewController

- (void)getMobId
{
    // 构造自定义参数（可选）
    NSMutableDictionary *customParams = [NSMutableDictionary dictionary];
    customParams[@"type"] = @"zhuanti";
    customParams[@"sharethumb"] = self.sharethumb;
    customParams[@"sharetitle"] = self.sharetitle;
    customParams[@"subURL"] = self.subURL;
    // 根据路径、来源以及自定义参数构造scene
    MLSDKScene *scene = [[MLSDKScene alloc] initWithMLSDKPath:@"" source:@"iOS" params:customParams];
    // 请求MobId
    __weak typeof(self) weakSelf = self;
    [MobLink getMobId:scene result:^(NSString *mobid, NSError *error) {
        weakSelf.mobid = mobid;
    }];
}

- (void)back:(id)sender
{
    //返回
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) weak_self = self;
    
    self.newsTableView.backgroundColor = [UIColor whiteColor];
    self.newsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UILabel *linelab = [UILabel new];
    linelab.backgroundColor = [UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f];
    [self.topViewBar addSubview:linelab];
    [linelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.topViewBar);
        make.height.equalTo(@0.5f);
    }];
    
    UIButton *buttonback = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonback setImage:[UIImage imageNamed:@"button_back"] forState:UIControlStateNormal];
    [self.topViewBar addSubview:buttonback];
    [buttonback addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [buttonback mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.topViewBar).with.offset(8.0f);
        make.bottom.equalTo(self.topViewBar);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@44.0f);
    }];
 
    UIButton *buttonShare= [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonShare setImage:[UIImage imageNamed:@"button_news_detail_more"] forState:UIControlStateNormal];
    [buttonShare addTarget:self action:@selector(shareButtonOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.topViewBar addSubview:buttonShare];
    [buttonShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.topViewBar.mas_right).with.offset(-8.0f);
        make.bottom.equalTo(buttonback.mas_bottom);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@44.0f);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.text = @"专题";
    titleLabel.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:17.0f];
    [self.topViewBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.topViewBar);
        make.bottom.equalTo(self.topViewBar.mas_bottom).with.offset(-10.0f);
    }];
    
    self.newsTableView.delegate = self;
    self.newsTableView.dataSource = self;
    self.newsTableView.tableFooterView = [UIView new];
    
    [self.newsTableView registerNib:[UINib nibWithNibName:@"NewsFocusCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsFocusCell"];
    [self.newsTableView registerNib:[UINib nibWithNibName:@"NewsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsCell"];
    
    self.newsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //刷新数据
        [weak_self refreshData];
    }];
    
    
    //    [self.newsTableView addFooterWithCallback:^{
    //        [weak_self loadMore];
    //    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.newsTableView.mj_header beginRefreshing];
    });
    
    
}

- (void)shareButtonOnclick:(id)sender
{
    
    M_SpecialNews *focusNews_ = [self.focusNews objectAtIndex:0];
    NSString *shareUrl_=focusNews_.f_shareUrl;
    NSString *titleString=self.sharetitle;
    NSString *imgUrlString=self.sharethumb;
    
    if ([shareUrl_ rangeOfString:@"?"].location != NSNotFound)
    {
        shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&uct=%@",[ServiceNews getAuthCode]]];
        if (self.mobid) {
            shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&mobid=%@",self.mobid]];
        }
    } else {
        if (self.mobid) {
            shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"?mobid=%@",self.mobid]];
        }
    }
    
    [ShareService share:self url:shareUrl_ title:titleString image:imgUrlString completion:nil];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)refreshData
{
    self.selectedIndex = 0;
    self.headerScrollView = nil;
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    
    __weak typeof(self) weak_self = self;
    [ServiceNews doFetchSpecialNewsList:self.subURL success:^(id responseObject, NSString *message) {
        [weak_self.newsTableView.mj_header endRefreshing];
        weak_self.focusNews = [responseObject objectForKey:@"focus"];
        NSArray *listNews_ = [responseObject objectForKey:@"list"];
        weak_self.listNews = [NSMutableArray array];
        if (listNews_) {
            [weak_self.listNews addObjectsFromArray:listNews_];
        }
        
        if ([weak_self.focusNews count]) {
            weak_self.focusHandle = [weak_self.newsTableView dequeueReusableCellWithIdentifier:@"NewsFocusCell"];
            weak_self.focusHandle.newsDatas = weak_self.focusNews;
            weak_self.focusHandle.focusTapAtIndex = ^ (M_News *news_) {
                
                //焦点图点击
                [weak_self jumpToNewsDetail:news_];
                
            };
        }
        
        [weak_self.newsTableView reloadData];
    } failure:^(NSString *message) {
        [weak_self.newsTableView.mj_header endRefreshing];
        
    }];
}

//- (void)loadMore
//{
//    self.currentPageIndex ++;
//    if (self.requestHandle) {
//        [self.requestHandle cancel];
//        self.requestHandle = nil;
//    }
//
//    __weak typeof(self) weak_self = self;
//    [ServiceNews doFetchNewsList:RequestType_LoadMore subURL:self.subURL pageIndex:self.currentPageIndex pageSize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
//
//        [weak_self.newsTableView footerEndRefreshing];
//        NSArray *listNews_ = [responseObject objectForKey:@"list"];
//        if (listNews_) {
//            [weak_self.listNews addObjectsFromArray:listNews_];
//        }
//
//        [weak_self.newsTableView reloadData];
//
//    } failure:^(NSString *message) {
//        [weak_self.newsTableView headerEndRefreshing];
//    }];
//}

- (void)jumpToNewsDetail:(M_News *)news_
{
    
}

#pragma mark tableViewDatasouce Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!section) {
        if (self.focusNews) {
            return 1;
        }
        else {
            return 0;
        }
    }
    else {
        if ([self.listNews count] > self.selectedIndex) {
            NSDictionary *item = [self.listNews objectAtIndex:self.selectedIndex];
            NSArray *data = [item objectForKey:@"item"];
            return [data count];

        } else {
            return 0;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        //焦点图
        return self.focusHandle;
    }
    else {
        //普通新闻，一张图，标题
        NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
        NSDictionary *item = [self.listNews objectAtIndex:self.selectedIndex];
        NSArray *data = [item objectForKey:@"item"];
        M_SpecialNews *news = [data objectAtIndex:indexPath.row];
        cell.newsData = news;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        //焦点图
        return ScreenRectWidth * 0.5f;
    }
    else
    {
        return 100.0f;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section) {
        return 35.0f;
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.listNews && [self.listNews count] > 0 && section) {
        UIView *v = [UIView new];
        if (!self.headerScrollView) {
            self.tagsArray = [NSMutableArray array];
            self.headerScrollView = [UIScrollView new];
            self.headerScrollView.backgroundColor = [UIColor whiteColor];
            UIView *headerScrollViewContentView = [UIView new];
            headerScrollViewContentView.backgroundColor = [UIColor whiteColor];
            [self.headerScrollView addSubview:headerScrollViewContentView];
            
            UIView *headerPreView = nil;
            
            CGFloat headWidth = 0;
            CGFloat distance = 15.0f;
            
            for (NSInteger i=0; i<[self.listNews count]; i++) {
                NSString *title = [[self.listNews objectAtIndex:i] objectForKey:@"name"];
                //添加导航
                UILabel *labelTitle = [UILabel new];
                labelTitle.backgroundColor = [UIColor clearColor];
                labelTitle.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:16.0f];
                labelTitle.textAlignment = NSTextAlignmentCenter;
                labelTitle.text = title;
                labelTitle.tag = i;
                
                CGSize sizeString = [title sizeWithAttributes:@{NSFontAttributeName:labelTitle.font}];
                CGFloat sizeWidth = sizeString.width + distance;
                headWidth += sizeWidth;
                
                [headerScrollViewContentView addSubview:labelTitle];
                [labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
                    if (!headerPreView) {
                        make.left.equalTo(labelTitle.superview);
                    }
                    else {
                        make.left.mas_equalTo(headerPreView.mas_right);
                    }
                    
                    make.top.bottom.equalTo(labelTitle.superview);
                    make.width.equalTo( @(sizeWidth) );
                    
                }];
                headerPreView = labelTitle;
                
                UITapGestureRecognizer *tagTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagTap:)];
                [labelTitle addGestureRecognizer:tagTap];
                labelTitle.userInteractionEnabled = YES;
                [self.tagsArray addObject:labelTitle];
            }
            
            [headerScrollViewContentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.headerScrollView).insets(UIEdgeInsetsZero);
                make.height.mas_equalTo(self.headerScrollView.mas_height);
                make.width.equalTo(@(headWidth));
            }];
            
            self.selectedIndex = -1;
            self.selectedIndex = 0;
        }
        
        [v addSubview:self.headerScrollView];
        [self.headerScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.headerScrollView.superview);
        }];
        
        return v;
    } else {
        return nil;
    }

}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    __weak typeof(self) weak_self = self;
    
    if (selectedIndex>=0 && self.selectedIndex != selectedIndex) {
        UILabel *labelTitle = [self.tagsArray objectAtIndex:selectedIndex];
        
        //判断标签右边是否完全显示
        if (labelTitle.frame.origin.x +labelTitle.frame.size.width - self.headerScrollView.contentOffset.x > self.headerScrollView.frame.size.width) {
            CGFloat x = self.headerScrollView.contentOffset.x - (self.headerScrollView.contentOffset.x - labelTitle.frame.origin.x + self.headerScrollView.frame.size.width - labelTitle.frame.size.width);
            [self.headerScrollView setContentOffset:CGPointMake(x, 0) animated:YES];
        }
        
        //判断标签右边是否完全显示
        if (labelTitle.frame.origin.x < self.headerScrollView.contentOffset.x) {
            CGFloat x = labelTitle.frame.origin.x;
            [self.headerScrollView setContentOffset:CGPointMake(x, 0) animated:YES];
        }
        
        NSInteger preIndex = self.selectedIndex;
        
        if (preIndex >=0) {
            UILabel *labelPre = [weak_self.tagsArray objectAtIndex:preIndex];
            labelPre.textColor = [UIColor blackColor];
        }
        
        labelTitle.textColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
        [UIView animateWithDuration:.1f animations:^{
            [labelTitle.superview layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
    }
    
    _selectedIndex = selectedIndex;
}

//标签点击
- (void)tagTap:(UITapGestureRecognizer *)ges
{
    NSInteger index = ges.view.tag;
    self.selectedIndex = index;
    [self.newsTableView reloadData];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section) {
        NSDictionary *item = [self.listNews objectAtIndex:self.selectedIndex];
        NSArray *data = [item objectForKey:@"item"];
        M_SpecialNews *news = [data objectAtIndex:indexPath.row];
        
        [ServiceNews doSendRead:news.f_id
                        success:^(id responseObject, NSString *message)
         {}
                        failure:^(NSString *message)
         {}];
        //新版本增加了f_commentsUrl
        if (news.f_commentsUrl!=nil && [news.f_commentsUrl rangeOfString:@"type=forward"].location != NSNotFound) {
            //外链新闻以及H5
            NewsWebViewController *controller = [NewsWebViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.urlString = news.f_commentsUrl;
            controller.imgUrlString = news.f_thumb;
            controller.titleString = news.f_title;
            if ([news.f_commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
            {
                controller.hasShare = YES;
            }
            if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
                [self showViewController:controller sender:self];
            }else{
                [self.navigationController pushViewController:controller animated:YES];
            }
        }else {
            NewsDetailViewController *controller = [NewsDetailViewController new];
            controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news.f_cid];
            controller.f_thumbnail = news.f_thumb;
            if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
                [self showViewController:controller sender:self];
            }else{
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
    }
}

@end
